package cn.wolfcode.luowowo.website.web.resolver;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.web.annotation.UserParam;
import cn.wolfcode.luowowo.website.web.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//自定义用户参数解析器
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver{

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    //该解析器支持哪一种类型参数:UserInfo
    //如果返回false,不支持解析,不执行resolverArgument方法, true表示支持解析,马上执行resolverArgument方法
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        //必须贴有该注解并且参数类型必须与下面字节码对象匹配才会注入属性
        //如果与该字节码对象相同才进行属性注入
        return methodParameter.
                hasParameterAnnotation(UserParam.class)
                &&methodParameter.getParameterType() == UserInfo.class;
    }

    //当上面supportsParameter 返回true时,执行
    //将上面支持类型,转换具体实例,注入请求映射方法的形参上
    //把该方法的返回值注入到参数上
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer
            , NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {

        //此处功能:获取当前登录用户对象,并将该对象注入到请求映射方法的形式参数上

        HttpServletRequest req = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse resp = nativeWebRequest.getNativeResponse(HttpServletResponse.class);

        String token = CookieUtil.getToken(req, resp);
        UserInfo userInfo = userInfoRedisService.getUserByToken(token);

        return userInfo;
    }
}
